<template>
  <view class="parent-elemet">
    
    <view class="item-first">
      <up-input
        prefixIcon="search"
        prefixIconStyle="font-size: 22px;color: #909399"
        placeholder="搜索飞手、订单、资讯"
        border="surround"
        v-model="dataInfo.val"
        @change="change"
      ></up-input>
      <view class="icon">
        <up-icon name="bell" color="#409eff" size="30"></up-icon>
      </view>
    </view>
    <view class="item-content">
      <view class="item-title">
        <text>热门飞手</text>
        <text @click="navigateTo(`/indexPages/index/pilotsList`)">更多飞手</text>
      </view>
      <view class="content">
        <up-scroll-list
          :indicator="false"
          indicatorColor="#fff0f0"
          indicatorActiveColor="#f56c6c"
        >
          <view
            v-for="(item, index) in dataList"
            :key="index"
            :style="{ width: modelWidth }"
            @click="viewDetails(item, `/detailsPages/details/flyingHandDetails`)"
            class="item-scroll"
          >
            <view class="item-top">
              <up-image
                :show-loading="true"
                shape="circle"
                :src="item.url"
                width="40px"
                height="40px"
              ></up-image>
              <text class="vip">{{ item.vip }}</text>
              <text class="name">{{ item.name }}</text>
            </view>
            <view class="item-top item-address">
              <up-icon name="map" size="30"></up-icon>
              <text>{{ item.address }}</text>
            </view>
            <view v-if="item.flightYears" class="item-info">
              <text>飞龄: {{ item.flightYears }}年</text>
            </view>
          </view>
          <!-- 如果没有飞手数据，显示提示 -->
          <view v-if="dataList.length === 0" class="empty-tip">
            <text>暂无认证飞手</text>
          </view>
        </up-scroll-list>
      </view>
    </view>
    <view class="popular-forums">
      <view class="item-title">
        <text>热门论坛</text>
        <text @click="navigateTo(`/indexPages/index/popularForum`)">更多论坛</text>
      </view>
      <view class="forum">
        <view
          class="item-forum"
          v-for="(item, index) in forumList"
          :key="index"
          @click="viewDetails(item, `/socialPages/social/postDetails`)"
        >
          <up-image
            :show-loading="true"
            shape="circle"
            :src="item.url"
            width="40px"
            height="40px"
          ></up-image>
          <view class="forum-right">
            <text>{{ item.content }}</text>
            <view class="item-footer">
              <text class="item-left">{{ item.name }}</text>
              <up-icon name="eye" size="20"></up-icon>
              <text class="item-right">{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
  <tabbar v-model:tabbarIndex="tabbarIndex"></tabbar>
</template>
<script setup lang="ts">
import tabbar from "@/components/tabbar.vue";
import { useUserIdentity } from '@/composables/useUserIdentity';
import { onMounted } from 'vue';
import { getHotPilots, getUserIdentity } from '@/api/user';

// 用户身份管理
const { 
  isLoggedIn, 
  userTypeText, 
  isPilot, 
  isOrganization, 
  isApprovedPilot, 
  isApprovedOrganization,
  initUserIdentity,
  loading
} = useUserIdentity();

// 用户手机号（从store获取）
const phone = ref('');
const tabbarIndex = ref<any>(0);
const dataList = ref<any>([]);

 // 加载当前用户信息
const loadCurrentUserInfo = async () => {
  try {
    // 获取用户存储信息
    const userStore = uni.getStorageSync('user-store');
    if (!userStore) {
      dataList.value = [];
      return;
    }
    
    const userData = JSON.parse(userStore);
    phone.value = userData.phone || '';
    
    // 如果是飞手，显示自己的信息
    if (isPilot.value && isApprovedPilot.value) {
      // 调用API获取完整的飞手信息
      try {
        const result = await getUserIdentity();
        console.log('获取用户身份信息:', result);
        
        if (result.data && result.data.code === 200 && result.data.data.pilotProfile) {
          const profile = result.data.data.pilotProfile;
          dataList.value = [{
            id: profile.profileId,
            name: profile.realName || userData.phone || '我',
            url: profile.avatar || 'https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626',
            vip: '我的信息',
            address: profile.address || '未设置地址',
            phone: profile.phone,
            flightYears: profile.flightYears || 0
          }];
        } else {
          // 如果API调用失败，使用本地存储的信息
          dataList.value = [{
            id: userData.userId,
            name: userData.userName || userData.phone || '我',
            url: userData.avatar || 'https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626',
            vip: '我的信息',
            address: userData.address || '未设置地址',
            phone: userData.phone,
            flightYears: userData.flightYears || 0
          }];
        }
      } catch (error) {
        console.error('获取飞手信息失败:', error);
        // 出错时使用本地存储的信息
        dataList.value = [{
          id: userData.userId,
          name: userData.userName || userData.phone || '我',
          url: userData.avatar || 'https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626',
          vip: '我的信息',
          address: userData.address || '未设置地址',
          phone: userData.phone,
          flightYears: userData.flightYears || 0
        }];
      }
    } else {
      // 非飞手或未认证，显示空
      dataList.value = [];
    }
  } catch (error) {
    console.error('加载用户信息出错:', error);
    dataList.value = [];
  }
};

// 页面加载时初始化用户身份
onMounted(async () => {
  // 获取屏幕宽度
  uni.getSystemInfo({
    success: (res) => {
      modelWidth.value = res.screenWidth - 65 + "px";
    },
  });
  
  // 如果已登录，初始化用户身份并加载自己的信息
  if (isLoggedIn.value) {
    await initUserIdentity();
    await loadCurrentUserInfo();
  } else {
    // 未登录，显示空
    dataList.value = [];
  }
});
const forumList = ref<any>([
  {
    url:
      "https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626",
    content: "[无人机租赁] 正式与您相遇",
    name: "zyz",
    quantity: "22",
  },
  {
    url:
      "https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626",
    content: "《政策解读：新无人机飞行管理规定对飞手的影响及应对策略》",
    name: "zyz",
    quantity: "22",
  },
  {
    url:
      "https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626",
    content: "无人机飞手如何在旅游航拍中捕捉独特视角",
    name: "zyz",
    quantity: "22",
  },
  {
    url:
      "https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626",
    content: "《政策解读：新无人机飞行管理规定对飞手的影响及应对策略》",
    name: "zyz",
    quantity: "22",
  },
  {
    url:
      "https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626",
    content: "无人机飞手如何在旅游航拍中捕捉独特视角",
    name: "zyz",
    quantity: "22",
  },
  {
    url:
      "https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626",
    content: "《政策解读：新无人机飞行管理规定对飞手的影响及应对策略》",
    name: "zyz",
    quantity: "22",
  },
  {
    url:
      "https://img2.baidu.com/it/u=3094987369,2055473366&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=626",
    content: "无人机飞手如何在旅游航拍中捕捉独特视角",
    name: "zyz",
    quantity: "22",
  },
]);
const dataInfo = ref<any>({});
const modelWidth = ref<any>();
const change = () => {};
const viewDetails = (item: any, url: any) => {
  navigateTo(url);
};
const navigateTo = (url: any) => {
  uni.navigateTo({
    url,
  });
};
</script>

<style lang="scss" scoped>
.parent-elemet {
  // padding: 10px;
  height: 100vh;
  overflow: auto;
  padding-bottom: 200px;
  .item-first {
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 10px;
    .icon {
      padding: 0px 30px;
    }
  }
  .item-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 60px;
    text {
      &:nth-child(1) {
        font-size: 18px;
        font-weight: bold;
      }
      &:nth-child(2) {
        font-size: 14px;
        color: #409eff;
      }
    }
  }
  .item-content {
    background-color: #f9fafb;
    padding: 0 10px;
    .content {
      display: flex;
      width: 100%;
      overflow: auto;
      .item-scroll {
        border-radius: 4px;
        border: 1px solid #f0f0f0;
        padding: 20px;
        display: flex;
        flex-direction: column;
        &:not(:first-child) {
          margin-left: 10px;
        }
        .item-top {
          display: flex;
          align-items: center;
          &.item-address {
            margin-top: 10px;
          }
          .vip {
            height: 25px;
            line-height: 25px;
            padding: 0 8px;
            background-color: #ffdc00;
            border-radius: 8px;
            color: white;
            margin: 0 10px 0 30px;
          }
          .name {
            font-size: 18px;
            font-weight: 800;
          }
        }
        .item-info {
          margin-top: 8px;
          font-size: 14px;
          color: #666;
          display: flex;
          align-items: center;
        }
      }
      .empty-tip {
        text-align: center;
        padding: 30px;
        color: #999;
        font-size: 14px;
      }
    }
  }
  .popular-forums {
    padding: 0 10px;
    .item-forum {
      display: flex;
      align-items: center;
      padding: 10px;
      border-radius: 4px;
      border: 1px solid #f0f0f0;
      &:not(:first-child) {
        margin-top: 10px;
      }
      .forum-right {
        margin-left: 30px;
      }
      .item-footer {
        display: flex;
        align-items: center;
        margin-top: 5px;
        text {
          font-size: 14px;
          &:nth-child(2) {
            padding: 0 10px;
          }
        }
        .item-left {
          margin-right: 5px;
        }
        .item-right {
          margin-left: 5px;
        }
      }
    }
  }
  
}
</style>
